package com.hrsaas.ext.spider.test.handler;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;

/**
 * create by marico
 */
public class MD5Utils {

    private MD5Utils() {
    }

    /**
     * md5EncodeStr(加密普通字符串)
     *
     * @param param
     * @return 设定文件 String 返回类型
     * @throws
     */
    public static String md5EncodeStr(String param) {
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] byteArray = param.getBytes("UTF-8");
            byte[] md5Bytes = md5.digest(byteArray);
            StringBuilder hexValue = new StringBuilder();
            for (byte value : md5Bytes) {
                int val = ((int) value) & 0xff;
                if (val < 16) {
                    hexValue.append("0");
                }
                hexValue.append(Integer.toHexString(val));
            }

            return hexValue.toString();
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * getMd5FromFile(获取文件的MD5值)
     *
     * @param @param  file
     * @param @return
     * @param @throws FileNotFoundException    设定文件
     * @return String    返回类型
     * @throws
     */
    public static String getMd5FromFile(File file) {
        if (file == null || file.exists()) {
            throw new IllegalArgumentException("文件不存在");
        }

        String value = null;
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
            MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(byteBuffer);
            BigInteger bi = new BigInteger(1, md5.digest());
            value = bi.toString(16);
        } catch (Exception e) {
            
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    
                }
            }
        }
        return value;
    }
}
